package nciae.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import nciae.db.common.CommonResult;
import nciae.db.mapper.*;
import nciae.db.pojo.dto.FileTempDTO;
import nciae.db.pojo.dto.apiGetHomeWorkDetailDTO;
import nciae.db.pojo.entity.*;
import nciae.db.pojo.vo.ApiGetHomeWorkDetailVO;
import nciae.db.pojo.vo.ApiGetHomeWorkVO;
import nciae.db.pojo.vo.HomeworkVo;
import nciae.db.service.HomeworkService;
import nciae.db.utils.FileUploadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.sql.SQLOutput;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HomeworkServiceImpl extends ServiceImpl<HomeworkMapper, Homework> implements HomeworkService {
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private HomeworkDetailMapper homeWorkDetailMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HomeworkDetailMapper homeworkDetailMapper;

    @Override
    public CommonResult<List<HomeworkVo>> search( Integer page , Integer size,String project , String classs, String homeworkType,Integer Id) {
        CommonResult<List<HomeworkVo>> rs = new CommonResult<>();

        try{
            Page<Homework> pg = new Page<>(page,size);
            QueryWrapper<Homework> queryWrapper = new QueryWrapper<>();
            if(homeworkType!=null&&!homeworkType.isEmpty()){
                queryWrapper.eq("homework_type",homeworkType);
            }
            if(project!=null&&!project.isEmpty()){
                QueryWrapper<Project> wrapper = new QueryWrapper<>();
                wrapper.eq("project_name", project).last("limit 1");
                Project p = projectMapper.selectOne(wrapper);
                queryWrapper.eq("project_id", p.getId());
            }
            if(classs!=null&&!classs.isEmpty()){
                QueryWrapper<Classs> wrapper = new QueryWrapper<>();
                wrapper.eq("class_name", classs).last("limit 1");
                Classs c = classMapper.selectOne(wrapper);
                queryWrapper.eq("class_id", c.getId());
            }
            User user = userMapper.selectById(Id);
            if ("班主任".equals(user.getRole())) {
                QueryWrapper<Classs> wrapper = new QueryWrapper<>();
                wrapper.eq("charger_id", user.getId());
                List<Classs> classes = classMapper.selectList(wrapper);
                List<Integer> classIds = classes.stream().map(Classs::getId).collect(Collectors.toList());
                queryWrapper.in("class_id", classIds);
            }

            homeworkMapper.selectPage(pg,queryWrapper);
            List<Homework> list = pg.getRecords();
            List<HomeworkVo> listVO = getHomeworkVOs(list);
            long count = pg.getTotal();
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setCount(count);
            rs.setData(listVO);
            return rs;
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }
    private List<HomeworkVo> getHomeworkVOs(List<Homework> list) {
        ArrayList<HomeworkVo> homeworkVos = new ArrayList<>();
        for (Homework s:list){
            homeworkVos.add(getHomeworkVO(s));
        }
        return homeworkVos;
    }
    private HomeworkVo getHomeworkVO(Homework homework) {
        HomeworkVo homeworkVo = new HomeworkVo();
        BeanUtils.copyProperties(homework,homeworkVo);
        //设置学员对应的项目
        Integer projectId = homework.getProjectId();
        Project project = projectMapper.selectById(projectId);
        homeworkVo.setProject(project);

        //设置学员对应的班级
        Integer classId =homework.getClassId();
        Classs classs = classMapper.selectById(classId);
        homeworkVo.setClasss(classs);

        return homeworkVo;
    }
    @Override
    public CommonResult<Homework> homeworkSave(HomeworkVo homeworkVo) {
        String className=homeworkVo.getClasss().getClassName();
        Homework homework=new Homework();
        String projectName=homeworkVo.getProject().getProjectName();
        CommonResult<Homework> rs = new CommonResult();
        try {
            QueryWrapper<Classs> classQueryWrapper = new QueryWrapper<>();
            classQueryWrapper.select("id").eq("class_name", className);
            List<Classs> list = classMapper.selectList(classQueryWrapper);
            if (list.isEmpty()) {
                rs.setCode(-1);
                return rs;
            }
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.select("id").eq("project_name", projectName);
            List<Project> lists = projectMapper.selectList(projectQueryWrapper);
            if (lists.isEmpty()) {
                rs.setCode(-1);
                return rs;
            }
            Integer projectId = lists.get(0).getId();
            // 假设用户 id 是 Integer 类型，如果是 Long 类型，请相应修改
            Integer classId = list.get(0).getId();
            homework.setId(homeworkVo.getId());
            homework.setProjectId(projectId);
            homework.setTitle(homeworkVo.getTitle());
            homework.setUserId(homeworkVo.getUserId());
            homework.setBeginDate(homeworkVo.getBeginDate());
            homework.setEndDate(homeworkVo.getEndDate());
            homework.setStudentNum(homeworkVo.getStudentNum());
            homework.setHomeworkType(homeworkVo.getHomeworkType());
            homework.setClassId(classId);
            if(homework.getId() == null || homework.getId() == 0){
                homeworkMapper.insert(homework);
                rs.setCode(0);
                rs.setMsg("创建成功");
                rs.setData(homework);
            } else {
                // Existing Project
                int rows = homeworkMapper.updateById(homework);
                if(rows > 0){
                    rs.setCode(0);
                    rs.setMsg("更新成功");
                    rs.setData(homework);
                } else {
                    rs.setCode(-1);
                    rs.setMsg("项目不存在或更新失败");
                }
            }

        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误: " + e.getMessage());
            return rs;
        }
        return rs;
    }

    @Override
    public CommonResult<List<ApiGetHomeWorkVO>> apiGetHomeWork(Long projectId, Long classId, Long studentId) {
        CommonResult<List<ApiGetHomeWorkVO>> result = new CommonResult<>();
        ArrayList<ApiGetHomeWorkVO> apiGetHomeWorkVOS = new ArrayList<>();
        try{
            QueryWrapper<Homework> wrapper = new QueryWrapper<>();
            wrapper.eq("project_id", projectId)
                    .eq("class_id", classId);

            List<Homework> homeworkList = homeworkMapper.selectList(wrapper);
            for(Homework homework : homeworkList){
                ApiGetHomeWorkVO apiGetHomeWorkVO = new ApiGetHomeWorkVO();
                apiGetHomeWorkVO.setTitle(homework.getTitle());
                apiGetHomeWorkVO.setEndDate(homework.getEndDate());
                apiGetHomeWorkVO.setId(homework.getId());

                try {
                    Integer homeWorkId = homework.getId();
                    QueryWrapper<HomeworkDetail> HomeworkDetailWrapper = new QueryWrapper<>();
                    HomeworkDetailWrapper.eq("homework_id", homeWorkId).eq("student_id", studentId);
                    HomeworkDetail homeworkDetail = homeworkDetailMapper.selectOne(HomeworkDetailWrapper);
                    System.out.println(homeworkDetail == null);
                    apiGetHomeWorkVO.setSubmitted(!(homeworkDetail == null));
                } catch (Exception e) {
                    apiGetHomeWorkVO.setSubmitted(false);
                }

                apiGetHomeWorkVOS.add(apiGetHomeWorkVO);
            }

            result.setCode(0);
            result.setMsg("查询成功");
            result.setData(apiGetHomeWorkVOS);
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional
    public CommonResult<Boolean> apiSubmitHomeWorkNoFiles(Integer homeworkId, Integer studentId, String content) {
        CommonResult<Boolean> result = new CommonResult<>();
        try {
            HomeworkDetail homeWorkDetail = new HomeworkDetail();  //家庭作业细节的信息
            homeWorkDetail.setHomeworkId(homeworkId);
            homeWorkDetail.setStudentId(studentId);
            homeWorkDetail.setContent(content);
            // 创建一个 Timestamp 对象表示当前时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            // 调用 setSubmitDate 方法，将 Timestamp 对象传递给它
            homeWorkDetail.setSubmitDate(timestamp);
            homeWorkDetail.setIsRead(0);


            List<Student> studentList = studentMapper.selectList(new QueryWrapper<Student>().eq("id", studentId));
            Integer expertId = studentList.get(0).getExpertId();
            homeWorkDetail.setExpertId(expertId);
            Homework homework = homeworkMapper.selectById(homeworkId);
//           加一个判断查看是否是新提交的还是修改的
            HomeworkDetail homeworkDe= homeWorkDetailMapper.selectOne(new QueryWrapper<HomeworkDetail>().eq("homework_id", homeworkId).eq("student_id", studentId));
            int byId,i;
            if (homeworkDe == null) {
                 homework.setSubmitNum(homework.getSubmitNum() + 1);
                 byId = homeworkMapper.updateById(homework);
                 i = homeWorkDetailMapper.insert(homeWorkDetail);
            }
            else {
                homework.setSubmitNum(homework.getSubmitNum());
                byId = homeworkMapper.updateById(homework);
                i = homeWorkDetailMapper.update(homeWorkDetail, new QueryWrapper<HomeworkDetail>().eq("id",homeworkDe.getId()));
            }

            if(i > 0 && byId > 0){
                result.setCode(0);
                result.setMsg("提交成功");
                result.setData(true);
            }else{
                result.setCode(-1);
                result.setMsg("提交失败");
                result.setData(false);
            }
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    public CommonResult<ApiGetHomeWorkDetailVO> apiGetHomeWorkDetail(apiGetHomeWorkDetailDTO apiGetHomeWorkDetailDTO) {
        CommonResult<ApiGetHomeWorkDetailVO> result = new CommonResult<>();
        ApiGetHomeWorkDetailVO apiGetHomeWorkDetailVO = new ApiGetHomeWorkDetailVO();
        try{
            Integer homeworkId = apiGetHomeWorkDetailDTO.getHomeworkId();
            Integer studentId = apiGetHomeWorkDetailDTO.getStudentId();
            QueryWrapper<HomeworkDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("homework_id", homeworkId)
                    .eq("student_id", studentId);
            HomeworkDetail homeWorkDetail = homeWorkDetailMapper.selectOne(wrapper);
            if(homeWorkDetail == null){
                result.setCode(-1);
                result.setMsg("请作答");
                result.setData(null);
            }else{
                Homework homework = homeworkMapper.selectById(homeworkId);
                apiGetHomeWorkDetailVO.setEndDate(homework.getEndDate());
                apiGetHomeWorkDetailVO.setComment(homeWorkDetail.getComment());
                apiGetHomeWorkDetailVO.setScore(homeWorkDetail.getScore());
                apiGetHomeWorkDetailVO.setReadDate(homeWorkDetail.getReadDate());
                apiGetHomeWorkDetailVO.setIsRead(homeWorkDetail.getIsRead());
                apiGetHomeWorkDetailVO.setContent(homeWorkDetail.getContent());
                apiGetHomeWorkDetailVO.setImageUrls(getImageFileNames(studentId, homeworkId ,homeWorkDetail.getUrlImg()));
                System.out.println(apiGetHomeWorkDetailVO.getImageUrls());
                //根据路径查询所有文件名
                apiGetHomeWorkDetailVO.setFileNames(getFileNames(studentId, homeworkId, homeWorkDetail.getUrlFile()));
                result.setData(apiGetHomeWorkDetailVO);
                result.setCode(0);
                result.setMsg("查询成功");
            }

        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误: " + e.getMessage());
        }
        return result;
    }

    private List<String> getImageFileNames(Integer StudentId, Integer HomeWorkId, String urlImg) {
        if(urlImg == null){
            return new ArrayList<String>();
        }
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = urlImg;
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    //只获取文件名
                    fileNames.add(FileUploadUtils.FILE_URL+
                            "homeWorkFiles/" +
                            String.valueOf(StudentId) +
                            "/" + String.valueOf(HomeWorkId) +
                            "/" + "img/"+ file.getName());
                }
            }
        }
        return fileNames;
    }

    @Override
    public HomeworkVo getHomework(Integer id) {
        Homework homework = homeworkMapper.selectById(id);
        HomeworkVo homeworkVO= getHomeworkVO(homework);
        return homeworkVO;
    }

    private List<String> getFileNames(Integer StudentId, Integer HomeWorkId ,String url_file) {
        if(url_file == null){
            return new ArrayList<String>();
        }
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = url_file;
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    fileNames.add(FileUploadUtils.FILE_URL+ "homeWorkFiles/" + String.valueOf(StudentId) + "/" + String.valueOf(HomeWorkId) + "/" + "file/"+ file.getName());
                }
            }
        }
        return fileNames;
   }
    /*根据id删除作业信息*/
    public CommonResult<Boolean> deleteHomeworkById(List<Integer> ids){
        CommonResult<Boolean> commonResult = new CommonResult<>();
        for(Integer id:ids){
            homeWorkDetailMapper.deleteHomework(id);
        }
        int deletedCount = homeworkMapper.deleteBatchIds(ids);



        if (deletedCount > 0) {
            commonResult.setCode(0);
            commonResult.setMsg("删除成功");
            commonResult.setCount(deletedCount);
            commonResult.setData(true);
        } else {
            commonResult.setCode(0);
            commonResult.setMsg("没有记录被删除");
            commonResult.setCount(0);
            commonResult.setData(false);
        }
        return commonResult;
    }


}
